#include "serialportThread.h"
#include "mainwindow.h"

extern QString comtest;

serialportThread::serialportThread(QObject *parent): QObject(parent)
{
    this->moveToThread(&thread);
    thread.start();
}

void serialportThread::run()
{
    QSqlDatabase db = dbHelper::openConnection();
    QSqlQuery query(db);

    QString insertSql= "Select SerialPort,BaudRate From ConnectionInfo;";
    query.exec(insertSql);

    QString serialNamePort;
    QString baud="0";
    while(query.next()){
        serialNamePort=query.value("SerialPort").toString();
        baud=query.value("BaudRate").toString();
    }

    serialPort = new QSerialPort(this);
    serialPort->close();

    QSerialPort::BaudRate baudRate;

    if(baud=="115200"){
        baudRate = QSerialPort::Baud115200;
    }
    else if(baud=="4800")
    {
        baudRate = QSerialPort::Baud4800;
    }
    else if(baud=="9600")
    {
        baudRate = QSerialPort::Baud9600;
    }
    else
    {
        return;
    }

    serialPort->setDataBits(QSerialPort::Data8);
    serialPort->setParity(QSerialPort::NoParity);
    serialPort->setStopBits(QSerialPort::OneStop);
    serialPort->setFlowControl(QSerialPort::NoFlowControl);
    serialPort->setPortName(serialNamePort);
    serialPort->setBaudRate(baudRate);
    if(serialPort->open(QIODevice::ReadWrite)){
        qDebug()<<"success";
    }else{
        qDebug()<<"false";
    }
    connect(serialPort,SIGNAL(readyRead()),this,SLOT(serialPortRead_Slot()));// 串口读取
}

// 接收消息
void serialportThread::serialPortRead_Slot()
{
    QByteArray buffer = serialPort->readAll();
    QString ss;
    for(int c :buffer)
    {
        if(c>=0)
        {
            ss += QString(" %1")
                    .arg(c, 2, 16, QChar('0'));
        }
        else
        {
            ss += QString(" %1")
                    .arg(c+256, 2, 16, QChar('0'));
        }
    }
    QString Data=ss.remove(QRegExp("\\s"));

}

void serialportThread::serialPortSend(QByteArray data){
    serialPort->write(data);
}

void serialportThread::serialclose(){
    serialPort->close();
}
